<template>
  <div id="FormDialog">
    <el-row>
      <el-col :span="24" class="margin_col">
        <div class="always_handerOne1">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="0">
              <template slot="title">
                <div class="always_title1">
                  创建直播课
                </div>
              </template>
              <el-form
                :model="formData"
                ref="vForm"
                :rules="rules"
                label-position="center"
                label-width="120px"
                :size="medium"
                style="display: flex; justify-content: flex-start"
              >
                <el-form-item label="直播课名称" prop="teachcastName">
                  <el-input
                    v-model="formData.teachcastName"
                    type="text"
                    clearable
                    :disabled="!allDisable"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
                <el-form-item label="直播时间" prop="teachcastTime">
                  <el-date-picker
                    v-model="formData.teachcastTime"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    :disabled="!allDisable"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="直播教师" prop="teacherName">
                  <el-input
                    v-model="formData.teacherName"
                    type="text"
                    clearable
                    :disabled="true"
                    placeholder="请选择"
                  ></el-input>
                </el-form-item>
                <el-form-item label="直播内容" prop="teachcastContent">
                  <el-input
                    v-model="formData.teachcastContent"
                    type="text"
                    clearable
                    :disabled="!allDisable"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
                <el-form-item label="直播对象" prop="teachcastDepcName">
                  <el-input
                    v-model="formData.teachcastDepcName"
                    type="text"
                    clearable
                    :disabled="!allDisable"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
                <el-form-item label="组织单位" prop="orgname">
                  <el-input
                    v-model="formData.orgname"
                    type="text"
                    clearable
                    :disabled="!allDisable"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
                <el-form-item label="频道号" prop="channelid">
                  <el-input
                    v-model="formData.channelid"
                    type="text"
                    clearable
                    disabled
                    placeholder="系统生成"
                  ></el-input>
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-col>
      <el-col :span="24" class="margin_col" name="1">
        <div class="always_handerOne1">
<!--          <custom-buttons-->
<!--            @back="handleBack"-->
<!--            @confirm="handleConfirm"-->
<!--            @confirmzc="handleConfirmZc"-->
<!--            :handleShow="handleShow"-->
<!--            :handleShow1="handleShow"-->
<!--          ></custom-buttons>-->
        </div>
      </el-col>
      <el-col :span="24" class="margin_col" name="1">
        <div class="always_handerOne1">
          <custom-buttons
            @back="handleBack"
            @confirm="handleConfirm"
            @confirmzc="handleConfirmZc"
            :handleShow="handleShow"
            :handleShow1="handleShow"
          ></custom-buttons>
        </div>
      </el-col>
    </el-row>
<!--    人员选择-->
    <PeopleSelect
      ref="peopleSelect"
      :type="'multiple'"
      :isCheck="true"
      :open="peopleOpen"
      :isClear="isClear"
      @cancel="peopleOpen = false"
      @submit="submitPeople"
    ></PeopleSelect>
<!--    部门选择-->
    <!--    <DepartmentDialog-->
    <!--      ref="peopleSelect"-->
    <!--      :type="'multiple'"-->
    <!--      :isCheck="true"-->
    <!--    ></DepartmentDialog>-->
  </div>

</template>
<script>

import CustomButtons from "@/components/CustomButton/CustomButton.vue";
import PeopleSelect from "../../../components/Selection/index.vue";
import DepartmentDialog from "../../../components/DepartmentDialog/index.vue";
import {getToken} from "@/utils/auth";
import moment from 'moment';
// import {queryById, insertOrUpdate ,noticeFirmWechat, getSelectWork, getSelectWorkList,updateStateById} from "@/api/system/mis/manHour";
import {getInit, listInit,listInitNameAndId} from "@/api/system/mis/init";
import {delFileInfo, download, getFilePath, preview} from "@/api/system/sysFileInfo/fileInfo";
import {onlinePreview} from "@/api/system/mis/file";
import {
  addInitmsn, getInitmsn,
  listInitmsn,
  listInitmsnByProjectIdAndName,
  updateInitmsn
} from "@/api/system/mis/initmsn";
import {addWorkSchedule} from "@/api/system/mis/workSchedule";
import {addMiddle} from "@/api/system/notice/middle";
import {getMethod, postMethod} from "@/api/system/livelesson/quote";
import {insertOrUpdate} from "@/api/system/mis/manHour";

export default {
  components: {
    CustomButtons,
    PeopleSelect,
    DepartmentDialog,
  },
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 100
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf']
    }
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/system/fileInfo/upload',
      number: 0,
      uploadList: [],
      fileList: [],
      buttonShow: true,
      bigPrice: 0,
      buttonLoading: false,
      workOpen: false,
      loading: false,
      proOpen: false,
      taskOpen: false,
      peopleOpen: false,
      isClear: false,
      dialogImageUrl: "",
      dialogVisible: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      medium: "medium",
      activeNames: ["0", "1", "2"],
      addLineShow: true,
      tableData: [],
      taskTableData: [],
      peopleType: undefined,
      noticeFrom: {},
      hour: undefined,
      selectedRows: [],
      deptsOptions: [],
      finishOptions: [
        {
          value: '是',
          label: '是'
        },
        {
          value: '否',
          label: '否',
        }
      ],
      titleDrawer:'历史工时填写情况',
      // 工时填报表格数据
      manHourList: [],
      gist: false,
      proQuesDisabled: true,
      allDisable: true,
      flagNew: false,
      drawer: false,
      direction: 'rtl',
      handleShow: true,
      // 任务下发弹窗
      questDialog: false,
      projectOptions:[],
      questOptions:[],
      form: {},
      questData: {
        id: undefined,
        refId: undefined,
        hourSonId: undefined,
        status: undefined,
        projectName: undefined,
        projectCode: undefined,
        projectId: undefined,
        createByName: undefined,
        createBy: undefined,
        createTime: undefined,
        principalName: undefined,
        principalCode: undefined,
        planEndTime: undefined,
        remark: undefined,
        priority: undefined,
        estimateManHour: undefined,
        missionType: undefined,
        missionTheme: undefined,
      },
      reviewEventsOptionsList: [],
      listData: {},
      // 总条数
      total: 0,
      businessId: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: undefined,
        projectManagerName: undefined,
      },
      eventTitle: undefined,
      sonId: undefined,
      subject: '',
      formData: {
        id: undefined,
        teachcastName: undefined,
        teachcastContent: undefined,
        teacherName: undefined,
        teacherCode: undefined,
        orgname: undefined,
        teachcastTime: undefined,
        teachcastDepcName: undefined,
        channelid: undefined,
        createBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        completionStatus: undefined,
        proManHourDetails: [],
      },
      proManHourDetails: [],
      rules: {
        teachcastName: [
          { required: true, message: "直播课名称不能为空", trigger: "blur" }
        ],
        teachcastContent: [
          { required: true, message: "直播内容不能为空", trigger: "blur" }
        ],
        teacherName: [
          { required: true, message: "直播教师不能为空", trigger: "change" }
        ],
        teachcastTime: [
          { required: true, message: "直播时间不能为空", trigger: "change" }
        ],
        teachcastDepcName: [
          { required: true, message: "直播对象不能为空", trigger: "change" }
        ],
        orgname: [
          { required: true, message: "直播对象不能为空", trigger: "change" }
        ],
      },
    };
  },
  computed: {

  },
  watch: {
  },
  created() {
    this.formData.teacherName = this.$store.state.user.nikename
    this.formData.teacherCode = this.$store.state.user.name
    this.formData.createTime = new Date();
    console.log("user", this.$store.state.user)
    this.formData.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
    console.log(this.$route.query.isView)
    // this.selectProject();
    if (this.$route.query.id != undefined) {
      // this.selectQuest()
      // this.selectData(this.$route.query.id);
    }
    if (this.$route.query.isView === 'edit') {
      console.log(this.$route.query.id)
      this.selectWork(this.$route.query.id)
      this.proQuesDisabled =false
    }
    if (this.$route.query.isView === 'view') {
      this.proQuesDisabled =false
      this.addLineShow = false
      this.selectWork(this.$route.query.id)
      this.handleShow = false
      this.allDisable = false
    }
  },
  mounted() {
  },
  methods: {
    // 通过id查询
    selectData(id){
      // queryById(id).then(response => {
      //   this.formData = response.data;
      //   this.hour = response.data.manHour;
      //   this.title = "修改工时填报";
      //   let data = {
      //     ids: this.formData.questId,
      //   };
      //   this.queryFile(data)
      // });
    },
    // 修改查看
    selectWork(id){
      getMethod('/livelesson/teachcast/queryById/' + id).then(response => {
        this.formData = response.data;
        this.hour = response.data.manHour;
        this.title = "修改";
        let data = {
          id: this.formData.questId,
        };
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(row){
      this.$refs.vForm.validateField('completionStatus')
    },
    selectProject(){
      let queryParams = {
        accountCategory: 'TC项目',
        projectCategoryName: '计划项目'
      };
      listInitNameAndId(queryParams).then(response => {
        this.projectOptions = response.map(item => {
          return {
            label: item.projectName,
            value: item.id,
          };
        })
      })
    },
    selectQuest(projectId){
      let queryParams = {}
      if (this.$route.query.isView === 'view'){
        queryParams = {
          name: undefined,
          projectId: projectId
        }
      }else {
        queryParams = {
          name: this.$store.state.user.name,
          projectId: projectId
        }
      }
      // listInitmsnByProjectIdAndName(queryParams).then(response => {
      //   this.questOptions = response.map(item => {
      //     return {
      //       label: item.missionTheme,
      //       value: item.id,
      //     };
      //   })
      // });
    },
    //
    projectChange(row){
      const label = this.projectOptions.find(option => option.value === row.projectId).label;
      // this.selectQuest(row.projectId)
      row.projectName = label
      this.$set(row, 'questId','')
      this.$set(row, 'quest', '')
    },
    // 任务改变事件
    questChange(row){
      const label = this.questOptions.find(option => option.value === row.questId).label;
      row.quest = label
      let queryParams = {
        id: row.questId
      }
      // queryInitBy
      // getInitmsn(row.questId).then(response => {
      //   this.$set(row, 'projectName', response.data.projectName)
      //   this.$set(row, 'projectId', response.data.projectId)
      // });
    },
    handleChange(row){
      const label = this.questOptions.find(option => option.value === row).label;
      this.form.questName = label
    },
    // 下发操作
    distribute(row){
      if (row.id == undefined || row.id == null){
        this.handleConfirmZc('distribute')
      }else if (row.state == '已分享'){
        return this.$message.warning("已分享,请勿重复分享！")
      }else {
        getInit(row.projectId).then(response => {
          this.sonId = row.id
          this.questData.status = '未开始'
          this.questData.hourSonId = row.id
          this.questData.projectName = row.projectName
          this.questData.projectCode = response.data.projectCode
          this.questData.projectId = row.projectCode
          this.questData.createBy = this.$store.state.user.name
          this.questData.createTime = new Date()
          this.questData.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
          this.questDialog = true
        })
      }
    },
    // 通知操作
    notice(row){
      this.listData = row
      if (row.id == undefined || row.id == null){
        this.handleConfirmZc('notice')
      }else {
        this.businessId = row.refId
        this.peopleType = 'notice'
        this.peopleOpen =true
        this.isClear =true
      }
    },
    handleAssist(row){
      if (row.isAssist == '是'){
        row.state ='未分享'
      }else {
        row.state =''
      }
    },
    // 明日工作提交
    submitFormForWork(){
      this.$refs['form'].validate((valid) => {
        if (valid){
          addWorkSchedule(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.workOpen = false;
            this.handleBack()
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      })
    },
    //  新增任务确认按钮
    submitForm() {
      this.$refs['vFormQuest'].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          //获取文件的主键ID
          let fileData = "";
          for (let s = 0; s < this.tableData.length; s++) {
            if (this.tableData.length - 1 == s) {
              fileData += this.tableData[s].ID;
            } else {
              fileData += this.tableData[s].ID + ",";
            }
          }
          let submitData = {
            fileDatas: fileData,
            questData: this.questData,
          };
          if (this.questData.id != null) {
            updateInitmsn(submitData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.questDialog = false
              this.emptyQuest()
            }).finally(() => {
              this.buttonLoading = false
            })
          } else {
            addInitmsn(submitData).then(response => {
              this.$modal.msgSuccess('新增成功')
              updateStateById(this.sonId).then(response => {
                this.selectData(this.formData.id);
                this.emptyQuest()
                this.questDialog = false
              }).finally(() => {
                this.buttonLoading = false
              })
              this.questDialog = false
            }).finally(() => {
              this.buttonLoading = false
            })
          }
        }
      })
    },
    emptyQuest(){
      this.questData = {
        id: undefined,
        refId: undefined,
        hourSonId: undefined,
        status: undefined,
        projectName: undefined,
        projectCode: undefined,
        projectId: undefined,
        createByName: undefined,
        createBy: undefined,
        createTime: undefined,
        principalName: undefined,
        principalCode: undefined,
        planEndTime: undefined,
        remark: undefined,
        priority: undefined,
        estimateManHour: undefined,
        missionType: undefined,
        missionTheme: undefined,
      }
      this.tableData = []
      this.number = 0
      this.fileList = []
    },
    //  新增任务取消按钮
    filecancel() {
      this.questDialog = false;
      this.emptyQuest()
    },
    //文件上传
    handleBeforeUpload(file) {
      // 校检文件类型
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      this.$modal.loading('正在上传文件，请稍候...')
      this.number++
      return true
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError('上传文件失败，请重试')
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.tableData.push({
          fileName: res.data.fileName,
          fileSize: res.data.fileSize + 'KB',
          fileUrl: res.data.fileUrl,
          ID: res.data.id,
          businessKey: '',
          updateBy: res.data.updateBy,
          updateTime: res.data.updateTime,
          createBy: res.data.createBy,
          createByName: res.data.createByName,
          createTime: res.data.createTime,
          oldFileName: res.data.oldFileName
        })
        this.uploadList.push({
          name: res.data.fileName,
          url: res.data.url,
          ossId: res.data.ossId
        })
        this.uploadedSuccessfully();
      } else {
        this.number--
        this.$modal.closeLoading()
        this.$modal.msgError(res.msg)
        this.$refs.fileUpload.handleRemove(file)
        this.uploadedSuccessfully()
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList)
        this.uploadList = []
        this.number = 0
        this.$emit('input', this.listToString(this.fileList))
        this.$modal.closeLoading()
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].ossId + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
      new Date()
    },
    deleteSelectedRows(event) {
      event.stopPropagation()
      if (this.selectedRows.length == 0) {
        this.$modal.msgWarning("请先选择需要删除的文件");
        return;
      }
      //获取选中数据
      let ids = ''
      this.$confirm(`确定移除 ？`)
        .then(() => {
          this.selectedRows.forEach((row) => {
            if (row.id == undefined) {
              ids += row.ID + ','
            } else {
              ids += row.id + ','
            }
            const index = this.tableData.indexOf(row)
            if (index !== -1) {
              this.tableData.splice(index, 1)
              this.fileList.splice(index, 1)
            }
          })
          ids = ids.substring(0, ids.length - 1)
          delFileInfo(ids).then((res) => {
          })
          this.selectedRows = []
        })
        .catch(() => {
        })
    },
    //选中项目后保存操作
    submitPro(proList) {
      if (proList.length !== 1) {
        return this.$message.warning("请选择一条数据!");
      }
      this.formData.projectName = proList[0].projectName
      this.formData.projectCode = proList[0].projectCode
      this.formData.projectId = proList[0].id
      this.formData.projectManager = proList[0].projectManagerName
      this.formData.projectManagerCode = proList[0].projectManagerCode
      this.formData.quest = undefined
      this.formData.questId = undefined
      this.formData.predictManHour = undefined
      // 二次验证
      this.$refs.vForm.validateField('projectName')
      this.proOpen =false
    },
    //选中任务后保存操作
    submitTask(taskList) {
      if (taskList.length !== 1) {
        return this.$message.warning("请选择一条数据!");
      }
      this.formData.quest = taskList[0].missionTheme
      this.formData.questId = taskList[0].id
      this.formData.predictManHour = taskList[0].estimateManHour
      // 二次验证
      this.$refs.vForm.validateField('quest')
      this.taskOpen =false
    },
    openPrincipal(row){
      this.peopleOpen = true
      this.isClear = true
    },
    //选中人员后操作
    submitPeople(peopleList) {
      if (this.peopleType === 'notice'){
        this.noticeFrom.recipientName = ''
        this.noticeFrom.recipientCode = ''
        for (let i = 0; i < peopleList.length; i++){
          this.noticeFrom.recipientName += peopleList[i].userName + ','
          this.noticeFrom.recipientCode += peopleList[i].userId + ','
        }
        this.noticeFrom.recipientName = this.noticeFrom.recipientName.slice(0, -1)
        this.noticeFrom.recipientCode = this.noticeFrom.recipientCode.slice(0, -1)
        this.noticeFrom.businessId =this.businessId
        this.noticeFrom.noticeTitle = '工时填报内容'
        this.noticeFrom.noticeType = 'hour'
        this.noticeFrom.createByName = this.$store.state.user.nikename
        // 发送通知
        this.$modal.loading("通知中");
        addMiddle(this.noticeFrom).then(res => {
          if (res.code === 200) {
            let data = {
              listData:this.listData,
              recipientName:this.noticeFrom.recipientName,
              recipientCode:this.noticeFrom.recipientCode,
            }
            noticeFirmWechat(data).then(res => {
              this.$modal.msgSuccess('通知成功')
              this.$modal.closeLoading()
            })

          } else {
            this.$modal.error('通知失败')
            this.$modal.closeLoading()
          }
        })
      }else {
        //判断是单选还是多选
        if (peopleList.length != 1) {
          return this.$message.warning('请选择一个人员')
        }
        this.questData.principalName = peopleList[0].userName
        this.questData.principalCode = peopleList[0].userId
        this.$refs.vFormQuest.validateField('principalName')
      }
      this.peopleOpen = false
    },
    // 弹窗取消按钮按钮
    cancelForWork(){
      this.workOpen = false
    },
    // 弹窗取消按钮按钮
    cancel(){
      this.projectDialog =false
    },
    // 项目列表点击数据
    projectHandleChange(row){
      this.projectList = row;
    },
    // 通过任务id查询项目
    selectItem(refId){
      const id = refId
      if (id == null || id == undefined) {
        return ;
      }
      getInit(id).then(response => {
        this.formData.projectCode = response.data.projectCode
        this.formData.projectManagerCode = response.data.projectManagerCode
        this.formData.projectManager = response.data.projectManagerName
        let data = {
          ids: this.formData.questId,
        };
        getFilePath(data).then((res) => {
          res.data.forEach((item) => {
            item.fileSize += "KB";
            this.taskTableData.push({
              businessKey: item.businessKey,
              fileName: item.fileName,
              createByName: item.createByName,
              createTime: item.createTime,
              oldFileName: item.oldFileName,
              fileSize: item.fileSize,
              fileUrl: item.fileUrl,
              ID: item.id,
            });
          });
        });
      });
    },
    handleClose() {
      this.drawer = !this.drawer;
    },
    //保存
    handleConfirm() {
      var createdata = {
        name: this.formData.teachcastName,
        newScene: "alone",
        channelPasswd: "Abed1234",
        type: "normal",
        startTime: new Date(this.formData.teachcastTime).getTime(),
        template: "alone",
        pureRtcEnabled: "Y",
        linkMicLimit: "6",
        labelData: [],
        doubleTeacherType: "normal"
      };
      this.$refs["vForm"].validate((valid) => {
        if (valid) {
          this.$modal.loading("保存中");
          // 获取当前时间的毫秒级时间戳
          postMethod('/livelesson/teachcast/getSign', this.formData).then(response => {
            var sign = response.dataset.datas.sign;
            var timestamp = response.dataset.datas.timestamp;
            axios({
              method: 'post',
              // url: 'http://api.polyv.net/live/v3/channel/statistics/mic/list?appId=gk0zhmr4sp&sign=' + sign + '&timestamp=' + timestamp + "&page=1&size=1000&startDay=2024-1-1&endDay=2024-4-10",
              url: 'http://api.polyv.net/live/v4/channel/create?appId=gk0zhmr4sp&sign=' + sign + '&timestamp=' + timestamp,
              data: createdata,
              headers: {
                'Content-Type': 'application/json' // 设置Content-Type为application/json
              }
            }).then(res => {
              console.log(res.data.data.channelId)
              this.formData.channelid = res.data.data.channelId
              postMethod('/livelesson/teachcast/insertOrUpdate', this.formData).then(response => {
                this.$modal.msgSuccess("保存成功");
                this.$modal.closeLoading()
                this.handleBack()
              }).finally(() => {
                this.buttonLoading = false;
              });
            }).catch(err => {
              this.buttonLoading = false;
              this.$message.error('系统错误', err)
            });
          }).catch(err => {
            this.buttonLoading = false;
            this.$message.error('系统错误', err)
          });
        }
      });
    },
    // 暂存
    handleConfirmZc(row) {
      this.$refs["vForm"].validate((valid) => {
        if (valid) {
          this.formData.hour = this.hour
          for (let i = 0; i < this.formData.proManHourDetails.length; i++) {
            if (this.formData.proManHourDetails[i].reportingContent == undefined || this.formData.proManHourDetails[i].reportingContent == '') {
              return this.$message.warning("请填写报工内容中第" + (i + 1) + "行汇报内容")
            }
            if (this.formData.proManHourDetails[i].manHour == undefined || this.formData.proManHourDetails[i].manHour == '') {
              return this.$message.warning("请填写报工内容中第" + (i + 1) + "行工时")
            }
          }
          if (this.formData.proManHourDetails.length ==0){
            return this.$message.warning("请填写报工内容")
          }
          this.$modal.loading("保存中");
          insertOrUpdate(this.formData).then(response => {
            this.formData = response
            if (row == 'notice'){
              this.businessId = this.formData.id
              this.peopleType = 'notice'
              this.peopleOpen =true
              this.isClear =true
            }else if (row == 'distribute') {
              getInit(row.projectId).then(response => {
                this.sonId = row.id
                this.questData.status = '未开始'
                this.questData.hourSonId = this.formData.id
                this.questData.projectName = row.projectName
                this.questData.projectCode = response.data.projectCode
                this.questData.projectId = row.projectCode
                this.questData.createBy = this.$store.state.user.name
                this.questData.createTime = new Date()
                this.questData.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
                this.questDialog = true
              })
            }
            this.$modal.msgSuccess("保存成功");
            this.$modal.closeLoading()
          }).finally(() => {
            this.buttonLoading = false;
          });
        }
      });
    },
    handleSelectionChange(selection){
      this.proManHourDetails = selection
    },
    handleSelectionChangeFile(selection){
      this.selectedRows = selection
    },
    beforeRemoves(row) {
      this.$confirm(`确定移除 ${row.oldFileName}？`)
        .then(() => {
          const index = this.tableData.indexOf(row);
          if (index !== -1) {
            this.tableData.splice(index, 1);
            this.fileList.splice(index, 1);
          }
          let sa = "";
          if (row.id == undefined) {
            sa = row.ID;
          } else {
            sa = row.id;
          }
          delFileInfo(sa).then((res) => {});
          this.handleRemove(row, this.fileList);
        })
        .catch(() => {});
    },
    handlePictureCardPreview(row){
      this.$modal.loading("正在加载...");
      const fileExtension = row.oldFileName.split('.').pop();
      if (fileExtension === 'png' || fileExtension === 'jpg') {
        preview(row.ID).then((s) =>{
          if (s != ""){
            this.dialogImageUrl = window.URL.createObjectURL(new Blob([s], { type: "image/jpeg" }));
            this.fileDialogVisible = true;
            this.$modal.closeLoading();
            return;
          }
        })
      }else if (fileExtension === 'pdf'){
        preview(row.ID).then((response) =>{
          let blob = new Blob([response], { type: 'application/pdf;charset=utf-8' });
          const href = URL.createObjectURL(blob);
          this.$modal.closeLoading();
          window.open(href, 'newWindow');
        })
      } else if (fileExtension === 'xlsx' || fileExtension === 'xls'){
        this.$confirm('此类型文件不可预览, 是否下载?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.fileDownload(row)
        }).catch(() => {

        });
      } else {
        onlinePreview(row.ID).then((response) => {
          let blob = new Blob([response], { type: 'application/pdf;charset=utf-8' });
          const href = URL.createObjectURL(blob);
          this.$modal.closeLoading();
          window.open(href, 'newWindow');
        })
      }
    },
    downloadFile(row){
      this.$modal.loading("下载中")
      download(row.ID).then((rew) =>{
        this.$modal.closeLoading();
        // 创建临时的下载链接
        const url = window.URL.createObjectURL(rew);
        if (typeof window.chrome !== 'undefined') {
          // chrome
          const link = document.createElement('a');
          link.href = url;
          link.download = row.oldFileName;
          document.body.appendChild(link);
          link.click();
          setTimeout(() => {
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
          }, 100);
          // window.URL.revokeObjectURL(link.href); // 释放资源
          // window.open("D:/151.pdf")
        } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // IE
          // const blob = new Blob([rew],{ type: 'application/octet-stream' });
          window.navigator.msSaveBlob(rew,  row.oldFileName);
        } else {
          // Firefox
          const file = new File([rew],  row.oldFileName,{ type: 'application/octet-stream' });
          window.open(URL.createObjectURL(file));
        }

      }).finally(() =>{

      })
    },
    // 子表添加行
    addRow(){
      this.formData.proManHourDetails.push(Object.assign({},this.formData.proManHourDetails))
      // this.selectQuest();
    },
    // 子表添加行
    assign(row){
      // this.selectQuest();
      const newObj = {
        quest: row.missionTheme,
        questId: row.id,
        projectName: row.projectName,
        projectId: row.projectId
      };
      this.formData.proManHourDetails.push(newObj);
    },
    // 子表删除行
    removeRows(){
      if (this.proManHourDetails.length === 0){
        return this.$message.warning("请选择数据进行删除!");
      }
      for (let i = 0; i < this.proManHourDetails.length; i++) {
        const row = this.proManHourDetails[i];
        const index = this.formData.proManHourDetails.indexOf(row);
        this.formData.proManHourDetails.splice(index, 1);
      }
      this.clearSelection()
    },
    clearSelection() {
      this.$refs.table.clearSelection(); // 清空选择
    },
    // 项目名称点击事件
    projectClick() {
      this.proOpen =true;
    },
    // 任务名称点击事件
    questClick() {
      if (this.formData.projectId !== undefined && this.formData.projectId !== '') {
        this.taskOpen = true;
      } else {
        this.$message.warning("请先选择项目!")
      }
    },
    switchShowDrawer() {
      this.drawer = !this.drawer;
      if (this.formData.questId !== undefined && this.formData.questId !== '') {
        getSelectWorkList(this.formData.questId).then(response => {
          this.manHourList = response.data;
        });
      }else {
        this.resetList();
      }
    },
    // 取消 返回
    handleBack() {
      this.reset();
      this.$router.back();
      //   this.$router.push({
      //     path: "/everyWork/manHourList"
      //   });
    },
    resetList() {
      this.manHourList = {
        quest: undefined,
        reportingContent: undefined,
        manHour: undefined,
        createByName: undefined,
      }
    },
    reset() {
      this.formData = {
        id: undefined,
        teachcastName: undefined,
        teachcastContent: undefined,
        teacherName: undefined,
        teacherCode: undefined,
        orgname: undefined,
        teachcastTime: undefined,
        teachcastDepcName: undefined,
        channelid: undefined,
        createBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        completionStatus: undefined,
      };
    }
  },
};
</script>

<style lang="scss" scoped>
.el_col {
  display: flex;
  justify-content: space-evenly;
  align-content: center;
}

.card-container {
  height: 80%; /* 设置容器的高度为 100% */
  display: flex;
  flex-direction: column;
}

.card-item {
  flex: 1; /* 平分容器的宽度 */
}

#FormDialog {
  height: 100%;
  display: flex;
  flex-wrap: nowrap;
  flex-direction: column;
  justify-content: space-between;
  overflow: hidden;
}

.dialog-footer1 {
  width: 100%;
  height: 6vh;
  background: #ffffff;
  text-align: center;
  line-height: 6vh;
}

.el-card {
  margin-top: 10px;
  width: 100%;
  height: 200px;
  background-color: #ffffff;
}

.el-select {
  width: 100%;
}

.el-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.el-form-item {
  width: 30%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-table {
  min-height: 50% !important;
}

.always_handerOne {
  height: 80px;
  background-color: #ffffff;
  //border-radius: 14px;
}

.always_handerOne1 {
  height: auto;
  background-color: #ffffff;
  //border-radius: 14px;
  padding: 20px;
}

.always_title {
  font-size: 20px;
  font-weight: bold;
  line-height: 53px;
  margin-left: 30px;
}

.always_title1 {
  font-size: 18px;
  font-weight: bold;
  // line-height: 53px;
  margin-left: 15px;
  position: relative;
}

.always_title1 ::before {
  content: "|";
  flex-shrink: 0;
  width: 4px;
  height: 6%;
  margin-left: 12px;
  // background: #f90;
  color: #f90;
  position: absolute;
  left: -22px;
  margin-bottom: 12px;
}

.always_hander {
  background: url(../../../assets/images/header0.png);
  height: 20px;
  width: 100%;
}

.margin_col {
  margin-bottom: 20px;
}

.el_formContent .el-form-item {
  width: 50%;
}

.imageList {
  display: flex;
}

.demonstration {
  text-align: center;
}

.sel-width {
  width: 90%;
}

.el-header {
  padding: 0px 0px;
}

.el-radio-group {
  display: flex;
  line-height: 1;
  vertical-align: middle;
  font-size: 0;
}

.styleCentre {
  line-height: 2.5;
}

.style-Change {
  padding: 0px 0px;
  background: #ffffff;
}
</style>
<style scoped>
</style>
